// 回到之前建立的 app/router.options.ts 文件
import { cloneDeep } from 'lodash-es'
import type { RouterOptions } from '@nuxt/schema'
import { RouteRecordRaw } from 'vue-router'

// 定义一个可将只读属性去掉的 Writeable
type Writeable<T> = { -readonly [P in keyof T]: T[P] }

// https://router.vuejs.org/api/interfaces/routeroptions.html

/**
 * 修改路由 path，建议先看本函数之下的实现
 *
 * /ask => /
 * /ask/info => /info
 *
 */
const editPath = (routes: RouteRecordRaw[], subDomainPath: string) => {
    for (const key in routes) {
        if (routes[key].path.includes(subDomainPath)) {
            if (routes[key].path === subDomainPath) {
                routes[key].path = '/'
                routes[key].name = '/'
            } else {
                routes[key].path = routes[key].path.replace(subDomainPath + '/', '/')
            }
        }
        if (routes[key].children?.length) {
            routes[key].children = editPath(routes[key].children!, subDomainPath)
        }
    }
    return routes
}

export default <RouterOptions>{
    routes: (routes) => {
        // routes 是只读的，通过 Writeable 将其改为可写，并且进行深克隆，避免影响到原始数据（渲染->激活过程的数据可能受影响）
        let routesTemp = cloneDeep(routes as Writeable<RouteRecordRaw[]>)

        // 记录当前域名 - 只服务端记录，客户端直接访问就行
        const nodeReqHost = useNodeReqHost()
        if (process.server) {
            const { ssrContext } = useNuxtApp()
            nodeReqHost.value = ssrContext!.event.node.req.headers.host!.split(':')[0]
        }

        // 根据子域名完成路由的修改
        if (nodeReqHost.value == 'agent.super-aiagent.com') {
            // 修改原本的首页路由
            const oldIndex = getArrayKey(routesTemp, 'path', '/')
            routesTemp[oldIndex].path = '/'
            routesTemp[oldIndex].name = '/'

            // 修改 /ask 路由为首页
            routesTemp = editPath(routesTemp, "chatai")
            // 记录下当前已经通过子域名访问
            const subDomain = useSubDomain()
            subDomain.value = 'agent'
        }
        // 根据子域名完成路由的修改
        if (nodeReqHost.value == 'testagent.super-aiagent.com') {
            // 修改原本的首页路由
            const oldIndex = getArrayKey(routesTemp, 'path', '/')
            routesTemp[oldIndex].path = '/'
            routesTemp[oldIndex].name = '/'

            // 修改 /ask 路由为首页
            routesTemp = editPath(routesTemp, "chatai")
            // 记录下当前已经通过子域名访问
            const subDomain = useSubDomain()
            subDomain.value = 'testagent'
        } // 根据子域名完成路由的修改
        if (nodeReqHost.value == 'client.ynjxqy.com') {
            // 修改原本的首页路由
            const oldIndex = getArrayKey(routesTemp, 'path', '/')
            routesTemp[oldIndex].path = '/'
            routesTemp[oldIndex].name = '/'

            // 修改 /ask 路由为首页
            routesTemp = editPath(routesTemp, "chatai")
            // 记录下当前已经通过子域名访问
            const subDomain = useSubDomain()
            subDomain.value = 'client'
        }
        return routesTemp
    }
}
